var conn=null;
   var disconnect=0;
   var dial_toID="";
   var event_java=0;/*0:idle;  1:received answer and then call*/
  document.addEventListener('DOMContentLoaded', function () {
  // PeerJS server location
  
  /////////This server is closed 
  //var SERVER_IP = '112.74.114.167';
  //var SERVER_PORT = 9000;
  //////////This server is free
  var SERVER_IP = 'luojin.herokuapp.com';
  var SERVER_PORT = 80;
  
  // DOM elements manipulated as user interacts with the app
  var messageBox = document.querySelector('#messages');
  var callerIdEntry = document.querySelector('#caller-id');
  var connectBtn = document.querySelector('#connect');
  var recipientIdEntry = document.querySelector('#recipient-id');
  var dialBtn = document.querySelector('#dial');
  var SendBtn = document.querySelector('#sendmsg');
  var remoteVideo = document.querySelector('#remote-video');
  var localVideo = document.querySelector('#local-video');

  var isopen=0;
  // the ID set for this client
  var callerId = null;

  // PeerJS object, instantiated when this client connects with its
  // caller ID
  var peer = null;
  var peerd = null;

  // the local video stream captured with getUserMedia()
  var localStream = null;

  // DOM utilities
  var makePara = function (text) {
  	document.getElementById("messages").innerText=text;
    var p = document.createElement('p');
    p.innerText = text;
    return p;
  };

  var addMessage = function (para) {
  	return;
  //	document.getElementById("messages").innerText='<p>1111</p>';
	 
    if (messageBox.firstChild) {
      messageBox.insertBefore(para, messageBox.firstChild);
    }
    else {
      messageBox.appendChild(para);
    }
	 
  };
  	 
  	
	setTimeout("connect();",1000);
	setInterval(function(){V2Timer()}, 7000);
	function V2Timer()
	{
		if(peer)
		 	peer.socket._socket.send("crab");
	 	if(disconnect>0)
	 	{
	 		
	 		peer=null;
			disconnect=0;
			 if (!peer) 
			 {
			 	logMessage('connect   ');
				connect();
			 }
			 else
			 {
			 	logMessage('reconnect   ');
			 //	peer.reconnect();
			 }
		}
		if(event_java==1)
		{
			dial();
			 
		}
		if(isopen==60)
		{
		//	logMessage('close local stream! ');
		//	isopen=0;
		//	localStream.stop();
			

		}
		else if(isopen>0)
			isopen++;

	}

  var logError = function (text) {
    var p = makePara('ERROR: ' + text);
    p.style.color = 'red';
    addMessage(p);
  };

  var logMessage = function (text) {
    addMessage(makePara(text));
  };

  // get the local video and audio stream and show preview in the
  // "LOCAL" video element
  // successCb: has the signature successCb(stream); receives
  // the local video stream as an argument
  var getLocalStream = function (successCb) {

    if (localStream && successCb) {
         successCb(localStream);
	  logMessage('getLocalStream 0  ');
    }
    else {
      navigator.webkitGetUserMedia(
        {
          audio: true,
          video: {
                        mandatory: {
                            maxWidth: 640,
                            maxHeight: 480,
                            minWidth: 320,
                            minHeight: 240
                            }
                    }
        },

        function (stream) {
          localStream = stream;

          localVideo.src = window.URL.createObjectURL(stream);

          if (successCb) {
            successCb(stream);
          }
        },

        function (err) {
          logError('failed to access local camera');
          logError(err.message);
        }
      );
    }
  };

var  s_flag=0;
  // set the "REMOTE" video element source
  var showRemoteStream = function (stream) {
    remoteVideo.src = window.URL.createObjectURL(stream);
	BT_auto_conect=1;
 	if(s_flag==0)
	{
		s_flag=1;
		
		setTimeout("BT_search();",100);
	}

  };



  // set caller ID and connect to the PeerJS server
  var connect = function () {
    callerId = callerIdEntry.value;

    if (!callerId) {
      logError('please set caller ID first');
      return;
    }

	logMessage( callerId+' connect  to server ');
    try {
	//	alert("peer ");
      // create connection to the ID server
     /* This server is closed 
     peer = new Peer(callerId, {
      					host: SERVER_IP,
      					port: SERVER_PORT,
					config: {'iceServers': [
					{url: 'stun:112.74.114.167:3478'}
           				 ]}
	  			});
       */
       peer = new Peer(callerId, {
         				host: SERVER_IP,
      					port: SERVER_PORT,
					config: {'iceServers': [
					{url: 'stun:stun.anyfirewall.com:3478'},
					{
					    url: 'turn:turn.anyfirewall.com:443?transport=tcp',
					    credential: 'webrtc',
					    username: 'webrtc'
					},
					{url:'stun:stun.ekiga.net'},
					{url:'stun:stun.ideasip.com'},
					{url:'stun:stun.voipbuster.com'},
					{url:'stun:stun.voipstunt.com'},
					{url:'stun:stun.xten.com'}
           				 ]}
	  			});
     // peerd = new Peer(callerId+'d', {host: SERVER_IP, port: SERVER_PORT});

      // hack to get around the fact that if a server connection cannot
      // be established, the peer and its socket property both still have
      // open === true; instead, listen to the wrapped WebSocket
      // and show an error if its readyState becomes CLOSED
      peer.socket._socket.onclose = function () {
        logError('on close connection to server');
       
	 disconnect=1;
	 //peer.reconnect();
	 
      };

      // get local stream ready for incoming calls once the wrapped
      // WebSocket is open
      peer.socket._socket.onopen = function () {
     //  logMessage('getLocalStream  ');
     //   getLocalStream();
		 
      };


	peer.on('connection', function(con){
		// alert("connection");
		logMessage('data on connection! ');
	        con.on('data', function(data){
		 	//alert("12"+data);  
		//  con.send('on connection');
	        document.querySelector('#receive-id').value = data;
		 data_cmd(data);	
		 conn=con;
	    });
	});
	
      // handle events representing incoming calls
       peer.on('call', answer);
    }
    catch (e) {
      peer = null;
      logError('error while connecting to server');
    }
  };

  // make an outgoing call
  var dial = function () {


	BT_auto_conect=0;
   if(dial_toID.length==0)
    	//dial_toID = recipientIdEntry.value;
  	 dial_toID =current_call;//$('#day_id').val();
    if (!peer) {
      logError('please connect first1');
      return;
    }


	conn = peer.connect(dial_toID);
	conn.on('open', function(){
	 //	alert("conn1");
 	  	conn.send('on opened!');
	 	logMessage('data on opened! ');
	  	conn.on('data', function(data) {
			mesg_pro(data);
			logMessage("p2p: "+data);
			//data_cmd(data);	
   			document.querySelector('#receive-id').value = data;
  		});
	});
	
	
	logMessage('dialr ... getLocalStream  ');

 	getLocalStream();//luojin
 
    if (!localStream) {
	//  getLocalStream();//luojin	
         logMessage(' start    local camera');
      return;
    }

   

    if (!dial_toID) {
      logError('could not start call as no recipient ID is set');
      return;
    }

    getLocalStream(function (stream) {
      logMessage('outgoing call initiated');

	

      var call = peer.call(dial_toID, stream);

      call.on('stream', showRemoteStream);

      call.on('error', function (e) {
        logError('error with call');
        logError(e.message);
      });
    });
  };


  // answer an incoming call
  var answer = function (call) {
	
	location.hash ="#pageone";
    if (!peer) {
      logError('cannot answer a call without a connection');
      return;
    }
 //   	setTimeout("logMessage('close0..') ;logMessage('close..');",10000);

   logMessage('answer 11. getLocalStream  ');


   
   getLocalStream();//luojin
   
    if (!localStream) {
      logError('could not answer call as there is no localStream ready!');
     // return;
    }
	
    logMessage('incoming call answered');
    isopen=1;
    call.on('stream', showRemoteStream);

    if(localStream)
    {
    	call.answer(localStream);
    }
	
	
  
  };

 var send_mesg = function () {
 	 //alert(conn);
	 conn.send(document.querySelector('#send-id').value);
 }
 
  // wire up button events
  //connectBtn.addEventListener('click', connect);
  dialBtn.addEventListener('click', dial);
  SendBtn.addEventListener('click', send_mesg);
 
  if(UI_set==null)
  	UI_set= new _UISetting();
 
  window.call_java.JScallJava('get setting:',0);
 
  
});